﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using FluentAssertions;
using Grundy.Licensing.Server.Command;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;

namespace Grundy.Licensing.Server.Tests
{
    [TestClass]
    public class ServerTests
    {
        [TestMethod]
        public void Should_start_and_stop_server()
        {
            var serverConfiguration = GetServerConfiguration();
            var applicationState = Substitute.For<IApplication>();
            applicationState.GetLicenseServiceFactory().Returns(new LicenseServiceFactory(applicationState));

            var server = new LicenseServer(serverConfiguration, null, new LicenseServiceFactory(applicationState), applicationState.LicensingStrategyFactory);
            server.Start();
            Thread.Sleep(1000);
            server.IsStarted.Should().Be(true);
            server.Shutdown();
            Thread.Sleep(1000);
            server.IsStarted.Should().Be(false);
        }

        [TestMethod]
        public void Server_should_not_crash_on_malformed_request()
        {
            var application = Application.Instance;
            var client1 = new TcpClient();
            client1.Connect(IPAddress.Loopback, 2225);
            var buffer = UTF8Encoding.UTF8.GetBytes("Malformed message.");
            client1.GetStream().Write(buffer, 0, buffer.Length);
            var client2 = new TcpClient();
            client2.Connect(IPAddress.Loopback, 2225);
            client2.GetStream().Write(buffer, 0, buffer.Length);
            application.LicenseServer.Shutdown();
        }
        
        private ServerConfiguration GetServerConfiguration()
        {
            return new ServerConfiguration {Port = 2000};
        }
    }
}
